package com.wei.shopping.controller;

import com.wei.shopping.entrty.Result;
import com.wei.shopping.pojo.Login;
import com.wei.shopping.service.AdminService;
import com.wei.shopping.utils.ValidateCode;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {
    @Resource
    private AdminService adminService;
    /**
     * 管理员登陆
     * @param map
     * @return
     */
    @RequestMapping("/login")
    public Result login(@RequestBody Map map, HttpServletRequest request){
        String code = (String)map.get("code");
        String username = (String)map.get("username");
        String password = (String)map.get("password");
        String realcode = ValidateCode.getCode();
        if(code != null && realcode != null && code.equalsIgnoreCase(realcode)){
            //验证码正确
            try{
                //数据库查询，判断roleid是否大于1
                String passwords = new Md5Hash(password, "Campus-shops").toString();
                Login login = adminService.login(username, passwords);
                if(login != null){
                    //存在用户，判断roleid是否大于1
                    if(login.getRoleid() > 1){
                        //是管理员
                        HttpSession session = request.getSession();
                        session.setAttribute("username",username);
                        session.setAttribute("userid",login.getUserid());
                        return new Result(true,"登陆成功");
                    }else{
                        return new Result(false,"你没有权限");
                    }
                }else{
                    //不存在用户
                    return new Result(false,"用户或密码错误");
                }
            }catch(Exception e){
                e.printStackTrace();
                return new Result(false,"系统错误");
            }
        }else{
            return new Result(false,"验证码错误");
        }
    }
    @RequestMapping("/getusername")
    public Result getusername(HttpServletRequest request){
        HttpSession session = request.getSession();
        String username = (String)session.getAttribute("username");
        return new Result(true,"获取成功",username);
    }

    @RequestMapping("/quit")
    public Result quit(HttpSession session){
        session.removeAttribute("username");
        session.removeAttribute("userid");
        return new Result(true,"退出成功");
    }
}
